package com.leetcode.tree;

import com.study.common.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @program: leetcode
 * @author: jzhou
 * @date: 2022-11-18 11:57
 * @version: 1.0
 * @description: 给定一个二叉树的根节点 root ，返回 它的 前序 遍历 。 根左右
 * 进阶: 递归算法很简单，你可以通过迭代算法完成吗？
 **/
public class BinaryTreePreorderTraversal {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;

        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode pop = stack.pop();
            list.add(pop.val);

            if (pop.right != null) {
                stack.push(pop.right);
            }
            if (pop.left != null){
                stack.push(pop.left);
            }
        }
        return list;
    }
}
